import { defineStore } from 'pinia'

const STORAGE_KEY = 'product-cost-data'

export const useProductStore = defineStore('product', {
	state: () => ({
		products: [],
		nextProductId: 1
	}),

	actions: {
		load() {
			const data = uni.getStorageSync(STORAGE_KEY)
			if (data && data.products) {
				this.products = data.products
				this.nextProductId = data.nextProductId
			} else {
				// 初始化示例数据
				this.products = [
					{
						id: 1,
						name: '示例产品',
						accessories: [
							{ name: '配件A', price: 10, quantity: 1 },
							{ name: '配件B', price: 20, quantity: 2 }
						]
					}
				]
				this.nextProductId = 2
			}

			// 为每个产品计算总价
			this.products.forEach((product) => {
				product.accessories.forEach((acc) => {
					if (acc.quantity === undefined) {
						acc.quantity = 1
					}
				})
				product.totalPrice = product.accessories.reduce((sum, acc) => sum + acc.price * acc.quantity, 0)
			})
		},

		save() {
			const dataToSave = {
				products: this.products,
				nextProductId: this.nextProductId
			}
			uni.setStorageSync(STORAGE_KEY, JSON.parse(JSON.stringify(dataToSave)))
		},

		addProduct(name) {
			if (name) {
				this.products.push({
					id: this.nextProductId++,
					name,
					accessories: [],
					totalPrice: 0
				})
				this.save()
			}
		},

		deleteProduct(productId) {
			const index = this.products.findIndex((p) => p.id === productId)
			if (index !== -1) {
				this.products.splice(index, 1)
				this.save()
				if (this.products.length === 0) {
					uni.removeStorageSync(STORAGE_KEY)
				}
			}
		},

		addAccessory(productId, accessory) {
			const product = this.getProduct(productId)
			if (product && accessory.name && accessory.price > 0 && accessory.quantity > 0) {
				product.accessories.push(accessory)
				this.save()
			}
		},

		updateProductName(productId, newName) {
			const product = this.getProduct(productId)
			if (product && newName) {
				product.name = newName
				this.save()
			}
		},

		updateAccessory(productId, accessoryIndex, updatedAccessory) {
			const product = this.getProduct(productId)
			if (product && updatedAccessory.name && updatedAccessory.price > 0 && updatedAccessory.quantity > 0) {
				product.accessories[accessoryIndex] = updatedAccessory
				this.save()
			}
		},

		deleteAccessory(productId, accessoryIndex) {
			const product = this.getProduct(productId)
			if (product) {
				product.accessories.splice(accessoryIndex, 1)
				this.save()
			}
		}
	},

	getters: {
		getProduct: (state) => {
			return (id) => state.products.find((p) => p.id == id)
		}
	}
})
